/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.main;


import java.io.File;
import java.io.IOException;

import it.gashale.jacolib.core.EvalError;
import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.util.FileSystem;

public class JacolibArgumentEval {
	Jacolib jacolib;
	String clsh_name;
	
	public JacolibArgumentEval(Jacolib jacolib, String clsh_name) {
		this.jacolib=jacolib;
		this.clsh_name=clsh_name;
	}
	public Object[] eval(String args[], boolean tracep) throws EvalError, JacolibError {
		Object res[]=new Object[args.length];
		if(args.length>0) {
			for(int i=0; i<args.length; ++i) {
				if(tracep) System.out.println("Eval: "+args[i]);
				res[i]=eval(args[i]);
				if(tracep) System.out.println("Result: "+res[i]);
			}	
		}
		return res;
	}
	public Object eval(String arg) throws EvalError, JacolibError {
		Object res=null;
		String eval=null;
		boolean remote=true;
		
		File script=new File(arg);
		if(script.exists()) {
			try {
				eval=FileSystem.fileToSting(arg);
			} catch (IOException e) {
				throw new JacolibError(e.getMessage()); 
			}
			if(arg.endsWith(".js")) {
				remote=false;
			}
		} else {
			eval=arg;
			if(eval.startsWith("js:")) {
				eval=eval.substring(3);
				remote=false;
			} else if (eval.startsWith("cl:")) {
				eval=eval.substring(3);
			}
		}
		if(remote)
			res=jacolib.getRemoteShell(clsh_name).eval(eval);
		else
			res=jacolib.getShell().eval(eval);
		return res;
	}
}
